package com.ssm.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class FileDownloadUtil {

    private static final String UPLOADDIR ="download" ;

    public static void download(HttpServletRequest request,
                                HttpServletResponse response, String storeName,
                                String realName) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try{
            request.setCharacterEncoding("UTF-8");
            //获取下载路径
            String ctxPath = request.getServletContext()
                    .getRealPath("/")
                    +UPLOADDIR;
            String downLoadPath = ctxPath +"/"+ storeName;

            long fileLength = new File(downLoadPath).length();
            //设置响应头信息  text/html  application/json
            response.setContentType("application/octet-stream");//申明 文件的下载类型
            response.setHeader("Content-disposition", "attachment; filename=" + new String(realName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            //读取文件 并输出到 response中，最终相应给客户
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        finally {
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
